﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ShenLanCMS.Web
{
    /// <summary>
    /// 权限属性类,判断是否已经登录
    /// </summary>
    public class IsLogon : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //var db = new ShenLanCMS.Models.EntityContext();
            //var user = db.Users.SingleOrDefault(n => n.UserName == "administrator");
            //filterContext.HttpContext.Session["users"] = user;
            var user = filterContext.HttpContext.Session["users"];
            if (user == null)
            {
                //跳转页面
                var from = filterContext.HttpContext.Request.Url.AbsoluteUri;
                var error = "请登录再进行操作!";
                var url = string.Format("/user/logon?from={0}&error={1}", from, error);
                filterContext.Result = new RedirectResult(url);
            }

        }
    }

    /// <summary>
    /// 权限属性类,判断是否已经登录且是管理员
    /// </summary>
    public class IsAdmin : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //var db = new ShenLanCMS.Models.EntityContext();
            //var user = db.Users.SingleOrDefault(n => n.UserName == "administrator");
            //filterContext.HttpContext.Session["users"] = user;
            var user = filterContext.HttpContext.Session["users"];
            if (user == null)
            {
                //跳转页面
                var from = filterContext.HttpContext.Request.Url.AbsoluteUri;
                var error = "请登录再进行操作!";
                var url = string.Format("/user/logon?from={0}&error={1}", from, error);
                filterContext.Result = new RedirectResult(url);
            }
            else
            {
                var u = user as ShenLanCMS.Models.User;
                if (u.UserName.ToLower() != "administrator" && u.Status != 2)
                {
                    var url = string.Format("/home/error");
                    filterContext.Result = new RedirectResult(url);
                }
            }
        }
    }
}